package jjn.round2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-06-10 18:56
 */
public class LeetCode40_CombinationsII {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        boolean[] used = new boolean[candidates.length];
        backtrack(candidates, target, 0, new ArrayList<>(), result, 0, used);
        return result;
    }
    
    private void backtrack(int[] candidates, int target, int sum, List<Integer> path, List<List<Integer>> result, int startIndex, boolean[] used) {
        if (sum > target) {
            return;
        }
        if (target == sum) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            if (i >= 1 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
                continue;
            }
            path.add(candidates[i]);
            used[i] = true;
            backtrack(candidates, target, sum + candidates[i], path, result, i + 1, used);
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
}
